package cn.wolfcode.luowowo.website.controller;

import cn.wolfcode.luowowo.article.domain.Destination;
import cn.wolfcode.luowowo.article.domain.StrategyDetail;
import cn.wolfcode.luowowo.article.domain.Travel;
import cn.wolfcode.luowowo.article.domain.TravelContent;
import cn.wolfcode.luowowo.article.query.TravelQuery;
import cn.wolfcode.luowowo.article.service.IDestinationService;
import cn.wolfcode.luowowo.article.service.IStrategyDetailService;
import cn.wolfcode.luowowo.article.service.ITravelService;
import cn.wolfcode.luowowo.cache.service.IStrategyStatisRedisService;
import cn.wolfcode.luowowo.cache.service.ITravelStatisRedisService;
import cn.wolfcode.luowowo.cache.vo.StrategyStatisVO;
import cn.wolfcode.luowowo.comment.domain.TravelComment;
import cn.wolfcode.luowowo.comment.query.TravelCommentQuery;
import cn.wolfcode.luowowo.comment.service.ITravelCommentService;
import cn.wolfcode.luowowo.common.exception.LogicException;
import cn.wolfcode.luowowo.common.util.AjaxResult;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotation.UserParam;
import cn.wolfcode.luowowo.website.util.UMEditorUploader;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.Collections;
import java.util.List;

@Controller
@RequestMapping("travel")
public class TravelController {
    @Reference
    private ITravelService travelService;
    @Reference
    private IDestinationService destinationService;
    @Reference
    private IStrategyDetailService strategyDetailService;
    @Reference
    private ITravelCommentService travelCommentService;
    @Reference
    private ITravelStatisRedisService travelStatisRedisService;

    @RequestMapping("")
    public String list(Model model, @ModelAttribute("qo") TravelQuery qo,@UserParam UserInfo userInfo){

        model.addAttribute("pageInfo",travelService.query(qo));
        //todo 最新游记动态的显示
        List<TravelComment> tcs = travelCommentService.findFirstTen();
        model.addAttribute("tcs", tcs);

        return "travel/list";
    }


    @RequestMapping("/detail")
    public String detail(Model model,Long id){
        Travel detail = travelService.get(id);
        TravelContent content = travelService.getContent(id);
        //关联明细和内容
        detail.setTravelContent(content);



        //阅读量
        //设置方法使得阅读量+1,存储在redis缓存中
        travelStatisRedisService.viewNumIncrease(id,1);
        //从redis里面查出阅读量存入detail里面共享到前端
        detail.setViewnum(travelStatisRedisService.getTravelStatisVO(id).getViewnum());

        //收藏量
        detail.setFavornum(travelStatisRedisService.getTravelStatisVO(id).getFavornum());

        //顶
        detail.setThumbsupnum(travelStatisRedisService.getTravelStatisVO(id).getThumbsupnum());


        model.addAttribute("detail",detail);

        //吐司
        //根据明细获取该明细描述的目的地的id
        List<Destination> toasts = destinationService.getToasts(detail.getDest().getId());
        Destination dest = toasts.remove(toasts.size() - 1);
        model.addAttribute("toasts",toasts);

        //关联某个目的地下的攻略
        List<StrategyDetail> sds = strategyDetailService.getDetailTop3(detail.getDest().getId());
        model.addAttribute("sds",sds);
        //关联某个目的地下的游记
        List<Travel> ts = travelService.getViewNumTop3(detail.getDest().getId());
        model.addAttribute("ts",ts);

        TravelCommentQuery qo = new TravelCommentQuery();
        qo.setTravelId(id);
        qo.setCurrentPage(1);
       // qo.setPageSize(Integer.MAX_VALUE);
        Page page = travelCommentService.query(qo);
        //评论
        System.out.println(page.getContent());
        model.addAttribute("list", page.getContent());

        return "travel/detail";
    }


    @RequestMapping("/input")
    public String input(Model model,Long id){
        if (id != null){
            model.addAttribute("tv",travelService.get(id));
        }
        model.addAttribute("dests",destinationService.getDestByDeep(3));
        return "travel/input";
    }


    @Value("${file.path}")
    private String filePath;

    //上传图片
    @RequestMapping("/contentImage")
    @ResponseBody
    public String uploadUEImage(MultipartFile upfile, HttpServletRequest request) throws Exception{
        UMEditorUploader up = new UMEditorUploader(request);
        String[] fileType = {".gif" , ".png" , ".jpg" , ".jpeg" , ".bmp"};
        up.setAllowFiles(fileType);
        up.setMaxSize(10000); //单位KB
        up.upload(upfile, filePath);

        String callback = request.getParameter("callback");
        String result = "{\"name\":\""+ up.getFileName() +"\", \"originalName\": \""+ up.getOriginalName() +"\", \"size\": "+ up.getSize()
                +", \"state\": \""+ up.getState() +"\", \"type\": \""+ up.getType() +"\", \"url\": \""+ up.getUrl() +"\"}";
        result = result.replaceAll( "\\\\", "\\\\" );
        if(callback == null ){
            return result ;
        }else{
            return "<script>"+ callback +"(" + result + ")</script>";
        }
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody
    public Object saveOrUpDate(Travel travel,@UserParam UserInfo userInfo){
        //作者
        travel.setAuthor(userInfo);
        Long id = travelService.saveOrUpdate(travel);
        return AjaxResult.SUCCESS.addData(id);
    }

    //游记的评论:添加成功后,将评论的数据转换成html格式评论模块,返回页面时直接拼接在页面上
    @RequestMapping("/commentAdd")
    public String commentAdd(Model model,TravelComment travelComment,int floor, @UserParam UserInfo userInfo){
        if (userInfo==null){
            throw new LogicException("请先登录");
        }

        travelComment.setUserId(userInfo.getId());
        travelComment.setUsername(userInfo.getNickname());
        travelComment.setCity(userInfo.getCity());
        travelComment.setLevel(userInfo.getLevel());
        travelComment.setHeadUrl(userInfo.getHeadImgUrl());

        TravelComment c = travelCommentService.save(travelComment);
        System.out.println(c.getUsername());

        //新添加的数据
        model.addAttribute("c",c);
        model.addAttribute("floor",floor+1);
        return "travel/commentTpl";
    }



    //收藏
    @RequestMapping("/favor")
    @ResponseBody
    public Object favor(Long sid,@UserParam UserInfo userInfo){
        if (userInfo==null){
            AjaxResult result = new AjaxResult(false, "请先登陆");
            result.setCode(102);
            return result;
        }
        //收藏还是取消收藏,根据传回来的true还是false来决定
        boolean ret = travelStatisRedisService.favor(sid,userInfo.getId());
        return new  AjaxResult(ret,"").addData(travelStatisRedisService.getTravelStatisVO(sid));
    }

    //顶
    @RequestMapping("/travelThumbup")
    @ResponseBody
    public Object strategyThumbUp(Long sid,@UserParam UserInfo userInfo){
        if (userInfo==null){
            AjaxResult result = new AjaxResult(false, "请先登陆");
            result.setCode(102);
            return result;
        }
        boolean ret = travelStatisRedisService.thumbUp(sid, userInfo.getId());
        return new AjaxResult(ret,"").addData(travelStatisRedisService.getTravelStatisVO(sid));
    }


}